import json
import urllib.parse

import requests
import urllib3
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.utils.crypto import get_random_string
from django.views.decorators.csrf import csrf_exempt

from baobaoxiong.access_token import get_wxCode_token
from baobaoxiong.aliyun import send_sms
from baobaoxiong.check_phone import check_phone
from baobaoxiong.upload_down import upload_img
from vistor.models import *
from schoolmaster.models import School, Student
from baobaoxiong.demo import main

appid = 'wx2e91c008e2619eee'


@csrf_exempt
def judge_views(request):
    if request.method == 'POST':
        # uphone = request.POST.get('uphone')
        iv = request.POST.get('iv')
        encrypteddata = request.POST.get('encrypteddata')
        code = request.POST.get('code')
        if not Openid.objects.filter(code=code):
            return JsonResponse({'code': 'failed'})
        # 获取openid和sessionkey
        openid = Openid.objects.get(code=code)
        # 获取电话
        uphone = main(appid, openid.sessionkey, encrypteddata, iv)
        user = Users.objects.filter(uphone=uphone).first()
        if user:
            # 查到了用户表
            role = user.role
            if role.character == '家长':
                user.openid = openid.openid  # 第一次登录保存用户ID
                user.save()
                return JsonResponse({'role': '家长', 'uphone': uphone})

            elif role.character == '老师':
                user.openid = openid.openid
                user.save()
                return JsonResponse({'role': '老师', 'uphone': uphone})
        else:
            schoolmaster = School.objects.filter(headmasterphone=uphone).first()
            if schoolmaster:
                # 查到了园长表
                role = Role.objects.get(id=4)  # 园长
                user = Users()
                user.uphone = uphone
                user.role = role
                user.openid = openid.openid
                user.save()
                return JsonResponse({'role': '园长', 'uphone': uphone})
            else:
                # 用户表园长表都没有
                role = Role.objects.get(id=2)  # 游客
                user = Users()
                user.uphone = uphone
                user.role = role
                user.openid = openid.openid
                user.save()
                return JsonResponse({'role': '游客', 'uphone': uphone})

#@csrf_exempt
#def code_views(request):
#   if request.method == 'POST':
#        phone = request.POST.get('phone')
#       if check_phone(phone) == 'ok':
#           # 设置验证码
#           code = get_random_string(length=4, allowed_chars='0123456789')
#           # 发送短信验证码，返回发信结果：result
#           send_sms(phone, code)
#           # 将短信验证码返回前端判断
#           return JsonResponse({'status': 'ok', 'code': code})
#       else:
#           return JsonResponse({'status': 'failed'})


@csrf_exempt
def login_views(request):
    if request.method == 'POST':
        code = request.POST.get('code')  # 临时登录凭证
        params = {
            'appid': 'wx2e91c008e2619eee',
            'secret': '658feb5365456948f2e1b8167e0688e5',
            'js_code': code,
            'grant_type': 'authorization_code',
        }
        data = requests.get('https://api.weixin.qq.com/sns/jscode2session', params)
        data2 = data.json()
        # 用户唯一标识
        openid = data2['openid']
        sessionkey = data2['session_key']
        # 查看用户中存不存在openid
        if Users.objects.filter(openid=openid).exists():
            user_obj = Users.objects.get(openid=openid)
            status = user_obj.role_id  # 用户角色
            uphone = user_obj.uphone  # 用户电话

            # 家长
            if status == 1:
                dic = {
                    'login': 'ok',  # 判定是否绑定过
                    'role': '家长',  # 角色判定
                    'uphone': uphone,  # 电话
                 }
                return JsonResponse(dic)
            # 游客
            elif status == 2:
                dic = {
                    'login': 'ok',
                    'role': '游客',
                    'uphone': uphone,
                 }
                return JsonResponse(dic)

            elif status == 3:
                dic = {
                    'login': 'ok',
                    'role': '老师',
                    'uphone': uphone,
                 }
                return JsonResponse(dic)

            elif status == 4:
                dic = {
                    'login': 'ok',
                    'role': '园长',
                    'uphone': uphone,
                 }
                return JsonResponse(dic)

        else:
            if not Openid.objects.filter(code=code).exists():
                user = Openid()
                user.code = code
                user.sessionkey = sessionkey
                user.openid = openid
                user.save()
            return JsonResponse({'login': 'No'})


#def get_wxCode(request):
#    access_token = get_wxCode_token()  # 获取生成二维码的token
#    params = {
#       'path': 'pages/UserSearch/index/main?id=1',
#    }
#    header_dict = {
#        "Content-Type": "application/json"
#    }
#    url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' + access_token
#    data = requests.post(url, json=params, headers=header_dict)
#    with open('1.jpg', 'wb') as f:
#        f.write(data.content)
#    return HttpResponse('OK')
